package com.hjh.shirodemo.web.controller;

import com.hjh.shirodemo.entity.UserBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        SecurityUtils.getSubject().logout();
        return "login";
    }

    @RequestMapping("/dologin")
    public String dologin(String usrName, String usrPassword, Map<String,Object> map,HttpSession session){
        try {
            AuthenticationToken token = new UsernamePasswordToken(usrName,usrPassword);
            SecurityUtils.getSubject().login(token);
            UserBean user = (UserBean) SecurityUtils.getSubject().getPrincipal();
            session.setAttribute("user",user);
        } catch (AuthenticationException e) {
            map.put("msg",e.getMessage());
            return "login";
        }
        return "main";
    }
}
